package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.woniu.entity.PageData;
import com.woniu.entity.Result;
import com.woniu.entity.dto.QueryMessageDTO;
import com.woniu.pojo.Message;
import com.woniu.service.IMessageService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaosong
 * @since 2023-04-01
 */
@RestController
@RequestMapping("/message")
public class MessageController extends BaseController{
    @Autowired
    private IMessageService messageService;

    @PostMapping("/save")
    @ApiOperation("保存")
    public Result save(@RequestBody Message message){
        boolean flag = messageService.add(message);
        return toResult(flag);
    }
    @PostMapping("/update")
    @ApiOperation("更改")
    public Result update(@RequestBody Message message){
        boolean flag = messageService.updateMessage(message);
        return toResult(flag);
    }
    @GetMapping("/{id}")
    @ApiOperation("根据id查询")
    public Result selectMessageById(@PathVariable String id){
        Message message = messageService.getById(id);
        return toDataResult(message);
    }
    @DeleteMapping("/delete")
    @ApiOperation("删除")
    public Result deleteTrainer(@RequestBody List<String> ids) {
        boolean delete = messageService.removeBatchByIds(ids);
        return toResult(delete);
    }
    @GetMapping("/all")
    @ApiOperation("查询所有")
    public Result selectAllMessage() {
        List<Message> messageList = messageService.list();
        return toDataResult(messageList);
    }
    @PostMapping("/search/{currentPage}/{pageSize}")
    @ApiOperation("搜索+分页")
    public Result selectMessage(
            @PathVariable Integer currentPage,
            @PathVariable Integer pageSize,
            @RequestBody QueryMessageDTO messageDTO) {
        PageData pageData = messageService.select(currentPage, pageSize, messageDTO);
        return toDataResult(pageData);
    }
    @ApiOperation("导出数据")
    @PostMapping("/export")
    public void listSearch(@RequestBody(required = false) QueryMessageDTO messageDTO,
                           HttpServletResponse response) throws IOException {
        PageData pageData =  messageService.select(1, 1000, messageDTO);
        List<Message> messageList = (List<Message>) pageData.getData();
        EasyExcel.write(response.getOutputStream(), Message.class).sheet().doWrite(messageList);
    }
}
